package com.kyd.push.mq;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.exception.ONSClientException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * ProducerSend MQ生产者
 *
 * @author kejw on 2018/9/27
 */
@Slf4j
//@Component
public class ProducerSend {

	@Autowired(required = true)
	private static Producer producer;

	public void send(ProduceRequest request) {
		Message msg = new Message(request.getTopic(), request.getTagA(), request.getBodyBytes());

		// 设置代表消息的业务关键属性，请尽可能全局唯一
		// 以方便您在无法正常收到消息情况下，可通过 MQ 控制台查询消息并补发
		// 注意：不设置也不会影响消息正常收发
		if (StringUtils.isNotBlank(request.getMsgKey())) {
			msg.setKey(request.getMsgKey());
		}

		if (StringUtils.isNotBlank(request.getMsgId())) {
			msg.setMsgID(request.getMsgId());
		}

		try {
			SendResult result = producer.send(msg);
			if (result != null) {
				log.info("[MQ]发送, {}", result.toString());
			} else {
				log.warn("[MQ]发送失败");
			}
		} catch (ONSClientException e) {
			log.error("[MQ]发送失败", e.getMessage());
		}
	}
}
